// vars/sshDeploy.groovy

def call(body) {
    def config = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = config

    body()

    assert(config.APP_NAME)
    
    /* 构建环境 */
    // def PFILE = params.PROFILE
    def PFILE = 'k8s'
    /* 各环境部署服务器,一个环境部署多个主机使用逗号隔开 */
    def SVRS_ENV = config.HOSTS
    
    def APP_NAME = config.APP_NAME
    def REMOTE_APP_PATH = config.REMOTE_PATH  + "/" + APP_NAME
    def MVN_NAME = config.MVN
    def MVN_SETTINGS = config.MVN_SETTINGS
    def MVN_ARGS = config.MVN_ARGS
    def MVN_DEPLOY = true
    def JAR_FILE = 'target/' + APP_NAME + '.jar'
    def SHELL_FILE = 'target/run.sh'
    def CICD_APP = config.APP_NAME
    def CICD_REG = "registry.cn-hangzhou.aliyuncs.com/cdw"        
    def CICD_IMAGE = CICD_REG + "/" +CICD_APP
    def CICD_BRANCH = env.BRANCH_NAME
    def MICRO_SERVICE = false
    def TARGET_DIR = "./target"

    if(config.MICRO_SERVICE){
        MICRO_SERVICE = true
        TARGET_DIR = "./"+ APP_NAME +"/target"
    }else{
        MICRO_SERVICE = false
        TARGET_DIR = "./target"
    }

    if(CICD_BRANCH!='master'){
        CICD_NAMESPACE = config.NAMESPACE + '-' + CICD_BRANCH
    }else{
        CICD_NAMESPACE = config.NAMESPACE
    }

    if(MVN_SETTINGS == null){
        MVN_SETTINGS = '/maven-data/maven-settings.xml'
    }
 
    if(MVN_NAME == null){
        MVN_NAME = 'maven3'
    }

    if(MVN_ARGS==null){
      MVN_ARGS=''
    }

    if(config.MVN_DEPLOY){
      MVN_DEPLOY=config.MVN_DEPLOY
    }    

    stage('Checkout') {
      checkout scm    
    }
    
    if (env.BRANCH_NAME != 'master') {
        build_tag = "${env.BRANCH_NAME}-${env.BUILD_NUMBER}"
    }else{
        build_tag = "${env.BUILD_NUMBER}"
    }

    stage('Build') {  
      sh "mvn -U -Dmaven.test.skip=true -P${PFILE} -Dmaven.test.failure.ignore clean package install deploy ${MVN_ARGS} -s ${MVN_SETTINGS}"
    }
   
    stage('Image') {
        dir("${TARGET_DIR}"){
            echo "Build Docker Image Stage"
            def image = docker.build("${CICD_IMAGE}:${build_tag}")
                  
            docker.withRegistry("http://${CICD_REG}", 'aliyuncs-cdw') {
                image.push("${build_tag}")
                image.push("latest")
            }     
        }
    }

    stage('Deploy') {
        if (MVN_DEPLOY){
            dir("${TARGET_DIR}"){
                echo "Deploy"
                sh 'env'            
                sh "sed -i 's/<BUILD_TAG>/${build_tag}/' deployment.yaml" 
                sh "sed -i 's/<BRANCH>/${CICD_BRANCH}/'  deployment.yaml"
                sh "sed -i 's/<NAMESPACE>/${CICD_NAMESPACE}/'  deployment.yaml"

                sh "kubectl apply -f deployment.yaml --namespace=${CICD_NAMESPACE} --record"   
            }
        }else{
            echo "Deploy skip"
        }       
    }


}